#!/bin/sh

set -o nounset
set -o errexit

set -x

container=${CI_PROJECT_NAME}-$CI_COMMIT_REF_NAME
image_name=${DOCKER_REGISTRY}/${CI_PROJECT_NAME}-${CI_PROJECT_ID}:$CI_COMMIT_REF_NAME

stop_existing() {
    set +o errexit
    ps=`docker ps -a |grep -w ${CI_PROJECT_NAME}`
    if [ `echo $ps | wc -l` -gt 0 ]; then
        hash=`echo $ps | awk '{print $1}'`
        docker stop $hash
        docker rm $hash
    fi
    set -o errexit
}

start_new() {
    docker run --restart always -p8020:8000 --name $container -d ${image_name}
}

main() {
    docker pull ${image_name}
    stop_existing
    start_new
}

main $@;
